package com.heima.gateway.filter;


import com.alibaba.fastjson.JSON;
import com.heima.gateway.utlis.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author huan
 * @serial 每天一百行, 致敬未来的自己
 * @Description 全局过滤器
 */
@Component
@Slf4j
@Order(0)
public class AuthorizeFilter implements GlobalFilter {
    private static List<String> urlList = new ArrayList<>();

    // 初始化白名单 url路径
    static {
        urlList.add("/login/in");
        urlList.add("/v2/api-docs");
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        for (String url : urlList) {
            //2.判断当前的请求是否为白名单，如果是，直接放行
            if (request.getURI().getPath().contains(url)) {
                //放行
                return chain.filter(exchange);
            }
        }

        //3.获取当前用户的请求头jwt信息
        String jwtToken = request.getHeaders().getFirst("token");

        //4.判断当前令牌是否存在
        if (StringUtils.isBlank(jwtToken)) {
            //如果不存在，向客户端返回错误提示信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return writeMessage(exchange, "需要登录");
        }

        try {
            //5.如果令牌存在，解析jwt令牌，判断该令牌是否合法，如果不合法，则向客户端返回错误信息
            Claims claims = AppJwtUtil.getClaimsBody(jwtToken);
            //  -1：有效，0：有效，1：过期，2：过期
            int result = AppJwtUtil.verifyToken(claims);
            if (result == 0 || result == -1) {
                //5.1 合法，则向header中重新设置userId
                Integer id = claims.get("id", Integer.class);
                log.info("token网关校验成功      userid:{}  URL:{}", id, request.getURI().getPath());
                //重新设置token到header中
                request.mutate().header("userId", id.toString());
                // 返回结果
                return chain.filter(exchange);
            } else {
                return writeMessage(exchange, "认证失效，请重新登录");
            }
        } catch (Exception e) {
            log.error("token 校验失败 :{}", e);
            return writeMessage(exchange, "认证失效，请重新登录");
        }
    }

    /**
     * 返回错误提示信息
     *
     * @return
     */
    private Mono<Void> writeMessage(ServerWebExchange exchange, String message) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("errorMessage", message);
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //设置状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //response.setStatusCode(HttpStatus.OK);
        //设置返回类型
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        //设置返回数据
        DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONBytes(map));
        //响应数据回浏览器
        return response.writeWith(Flux.just(buffer));
    }
}
